/* eslint-disable no-console */
// 全局请求封装
import loginMethods from './login'

const http = {
  request: async function(params) {
    if (params.source != 'login' && util.judgeNull(uni.getStorageSync('Token'))) {
      if (http.getWxLoginTokenCount()) {
        http.noTokenShowModal();
      }
      return;
    }

    // 请求参数处理
    if (Object.prototype.toString.call(params.data) === '[object Array]') {
      params.data = JSON.stringify(params.data);
    } else if (Object.prototype.toString.call(params.data) === '[object Number]') {
      params.data = params.data + '';
    }

    // 刷新token
    if (!params.login && !getApp()?.globalData.isLanding && !params.isRefreshing) {
      await loginMethods.refreshToken()
    }
    // 发起请求
    return new Promise((resolve, reject) => {
      uni.request({
        dataType: 'json',
        responseType: params.responseType === undefined ? 'text' : params.responseType,
        header: {
          'content-type': 'application/json',
          Authorization: uni.getStorageSync('Token'),
          'X-Access-Token': uni.getStorageSync('Token'),
          'X-Login-Type': 'WECHAT'
        },
        url: (params.domain ? params.domain : import.meta.env.VITE_APP_BASE_API) + params.url,
        data: params.data,
        method: params.method === undefined ? 'POST' : params.method,
        success: (res) => {
          const responseData = res.data || {};

          // 请求小程序码
          if (params.responseType === 'arraybuffer' && res.statusCode === 200) {
            return resolve(responseData);
          }

          switch (responseData.code) {
            case 200:
              if (!responseData.success) {
                tip.toast(responseData.message);
              }
              resolve(responseData);
              break;
            case 401:
              // 重设登录后跳转地址
              loginMethods.setRouteUrlAfterLogin();
              uni.removeStorageSync('expiresTimeStamp');
              uni.removeStorageSync('loginUserInfo');
              uni.removeStorageSync('Token');
              if (!params.dontTrunLogin) {
                let content = uni.getStorageSync('hadLogin') ? '登录已过期，请重新登陆！' : '请先进行登录！';
                http.toReLaunchLogin('/pages/index/index', content);
              }
              resolve(responseData);
              break;
            case 403:
              tip.error('拒绝访问');
              break;
            case 404:
              break;
            case 500:
              this.onRequestFail(params, responseData);
              tip.toast(responseData.message);
              break;
            case 504:
              break;
            default:
              // if (!params.hasCatch) {
              //   tip.toast(responseData.message || 'Error');
              // }
              reject(responseData);
              break;
          }
        },
        fail: (err) => {
          tip.toast('请求失败', 1000, 'error');
          reject(err);
        }
      })
    })
  },

  onRequestFail: (params, responseData) => {
    console.error('============== 请求异常 ==============');
    console.log('接口地址: ', params.url);
    console.log('异常信息: ', responseData);
    console.error('============== 请求异常 end ==========');
  },

  post: (url, params, source) => {
    return new Promise((resolve, reject) => {
      let requestParam = {
        url: url,
        method: 'POST',
      }
      if (!util.judgeNull(params)) requestParam.data = {
        ...params
      };
      if (!util.judgeNull(source)) requestParam.source = source;
      http.request(requestParam).then((data) => {
        console.log('post请求 成功 ==》', data);
        resolve(data);
      }).catch((err) => {
        console.log('post请求 失败 ==》', err);
        reject(err);
      })
    })
  },
  get: (url, params, source) => {
    return new Promise((resolve, reject) => {
      let requestParam = {
        url: url,
        method: 'GET',
      }
      if (!util.judgeNull(params)) requestParam.data = {
        ...params
      };
      if (!util.judgeNull(source)) requestParam.source = source;
      http.request(requestParam).then((data) => {
        console.log('get请求 成功 ==》', data);
        resolve(data);
      }).catch((err) => {
        console.log('get请求 失败 ==》', err);
        reject(err);
      })
    })
  },


  authorize: () => {
    uni.authorize({
      scope: 'scope.userInfo',
      success() {
        console.log('获取授权');
        http.toWxUserInfoLogin()
      },
      fail() {
        console.log('未获取授权');
      }
    })
  },
  toWxUserInfoLogin: () => {
    tip.loading();
    let loginCode = util.getLoginCode();
    let userInfo = util.getUserInfo();
    loginCode.then(codeRes => {
      console.log('toWxUserInfoLogin ==> loginCode ==> codeRes', codeRes);

      return new Promise((resolve, reject) => {
        userInfo.then(res => {
          let userResult = res || {};
          let userInfo = userResult.userInfo || {};
          console.log('请求数据解析', userInfo);
          let loginParams = {
            // #ifdef MP-WEIXIN
            loginType: 'WECHAT',
            // #endif
            jsCode: codeRes.code,
            infoRes: userResult,
          }
          http.realToLogin(loginParams);
          resolve('成功 1 ==> ', userInfo);
        }).catch(err => {
          tip.hide();
          console.log('失败 1 ==> ', err);
          reject('失败 1 ==> ', err);
        })
      })
    }).then(res => {
      console.log('成功 2 ==> promise-res ==> ', res);
    }).catch(err => {
      console.log('失败 2 ==> userProfile-err ==> ', err);
    })
  },
  toReLaunchLogin: (reLaunchPage, content) => {
    uni.setStorageSync('loginAfterPage', reLaunchPage);
    http.noTokenShowModal(content);
  },
  noTokenShowModal: (content = "请先登录") => {
    uni.showModal({
      title: '提示',
      content: content,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          // #ifdef MP-WEIXIN
          http.toWxUserProfileLogin();
          // #endif
          // #ifdef APP-PLUS
          uni.navigateTo({
            url: '/pages/accountLogin/accountLogin'
          });
          // #endif
        } else if (res.cancel) {
          console.log('用户点击取消');
          uni.removeStorageSync('loginAfterPage');
        }
      }
    })
  },
  toWxUserProfileLogin: () => {
    tip.loading();
    let loginCode = util.getLoginCode();
    let userProFile = util.getUserProfile();
    loginCode.then(codeRes => {
      console.log('toWxUserProfileLogin ==> loginCode ==> codeRes', codeRes);

      return new Promise((resolve, reject) => {
        userProFile.then(res => {
          let userResult = res || {};
          let userInfo = userResult.userInfo || {};
          console.log('请求数据解析', userInfo);
          let loginParams = {
            // #ifdef MP-WEIXIN
            loginType: 'WECHAT',
            // #endif
            jsCode: codeRes.code,
            infoRes: userResult,
          }
          http.realToLogin(loginParams);

          resolve('成功 1 ==> ', userInfo);
        }).catch(err => {
          tip.hide();
          reject('失败 1 ==> ', err);
        })
      })
    }).then(res => {
      console.log('成功 2 ==> promise-res ==> ', res);
    }).catch(err => {
      console.log('失败 2 ==> userProfile-err ==> ', err);
    })
  },
  realToLogin: (params) => {
    http.post('/sys/jsCode2session2login', params, 'login').then((res) => {
      let result = res.result || {};
      http.loginSuccess(result, () => {
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          complete: () => {
            load.getAllData();
            let loginAfterPage = uni.getStorageSync('loginAfterPage');
            if (!util.judgeNull(loginAfterPage)) {
              uni.reLaunch({
                url: loginAfterPage,
                complete: () => {
                  uni.removeStorageSync('loginAfterPage');
                }
              });
            }
            // tip.hide();
          }
        })
      })
    }).catch(() => {
      tip.hide();
    })
  },
  /**
   * 登录成功后执行
   * @param {Object} result  登录成功返回的数据
   * @param {Object} fn 登录成功后的回调
   */
  loginSuccess: (result, fn) => {
    console.log('登录成功后，保存登陆信息 ==> ', result);
    // 保存登陆用户信息
    wx.setStorageSync('loginUserInfo', result.userInfo || {});
    // 保存成功登录标识,token过期判断
    wx.setStorageSync('hadLogin', true);
    const expiresTimeStamp = result.tokenExpireTime * 1000 / 2 + new Date().getTime();
    // 缓存token的过期时间
    uni.setStorageSync('expiresTimeStamp', expiresTimeStamp);

    wx.setStorageSync('Token', result.token); // 把token存入缓存，请求接口数据时要用
    if (fn) {
      fn()
    }
  },
  getWxLoginTokenCount: (source) => {
    if (uni.getStorageSync('WxLoginTokenCount')) {
      uni.setStorageSync('WxLoginTokenCount', uni.getStorageSync('WxLoginTokenCount') + 1);
    } else {
      uni.setStorageSync('WxLoginTokenCount', 1);
    }
    // if (source == 'index') {
    //   return uni.getStorageSync('WxLoginTokenCount') == 1;
    // } else {
    //   return uni.getStorageSync('WxLoginTokenCount') < 4;
    // }
    return uni.getStorageSync('WxLoginTokenCount') == 1;
  },
}
export default http
